<template>
    <div>
        <el-upload :class="{'isAdd': isAdd}" action="#" list-type="picture-card" :on-preview="onPreview" :on-remove="onRemove" :http-request="httpRequest" :limit="1" :file-list="list">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="preview.show" append-to-body>
            <img width="100%" :src="preview.url" alt="">
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request'
export default {
    props: {
        value: {
            type: String | Array,
            default: _ => []
        },
        limit: {
            type: Number,
            default: 1
        }
    },
    computed: {
        isAdd() {
            return this.list.length >= this.limit
        }
    },
    watch: {
        value: {
            immediate: true,
            handler(newV) {
                newV = newV ? newV : []
                if (typeof newV == 'string') {
                    this.list = newV.split(',').map((item, k) => ({
                        url: item,
                        name: 'fileName' + k
                    }))
                } else {
                    this.list = newV.map(item => ({
                        url: item.url,
                        name: item.name
                    }))
                }
            }
        }
    },
    data() {
        return {
            // 图片列表
            list: [],
            // 预览相关
            preview: {
                show: false,
                url: ''
            }
        }
    },
    methods: {
        // 预览
        onPreview(e) {
            this.preview = {
                url: e.url,
                show: true
            }
        },
        // 移除
        onRemove(_, fileList) {
            this.$emit('input', fileList)
        },
        // 自定义上传
        httpRequest(e) {
            let formData = new FormData()
            formData.append('file', e.file)
            request({
                url: '/en_upload',
                method: 'post',
                data: formData
            }).then(res => {
                this.list.push({
                    url: res.data.filePath,
                    name: res.data.fileName
                })
                this.$emit('input', this.list)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.isAdd {
    ::v-deep .el-upload.el-upload--picture-card {
        display: none;
    }
}
</style>